package com.mallsystem.goodsservice.service;

import com.mallsystem.common.bean.Goods;
import com.mallsystem.common.bean.Score;
import com.mallsystem.common.exception.AllException;
import com.mallsystem.common.service.ScoreService;
import com.mallsystem.goodsservice.mapper.GoodsMapper;
import com.mallsystem.goodsservice.mapper.ScoreMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ScoreServiceImpl implements ScoreService {
    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(Score score) throws AllException {
        if(goodsMapper.selectById(score.getGoodsId()) == null){
            throw new AllException("商品不存在，无法评价");
        }
        if(score.getScore() == null){
            throw new AllException("请填写评分！");
        }
        //添加评分
        scoreMapper.insert(score);
        //查询该商品所有评分
        List<Float> scoreList = scoreMapper.selectByGoodsId(score.getGoodsId());
        Float sum = 0F;
        for (Float s : scoreList) {
            sum += s;
        }
        Float avg = sum/scoreList.size();
        //给商品设置平均分
        Goods goods = new Goods();
        goods.setId(score.getGoodsId());
        goods.setScore(avg);
        goodsMapper.update(goods);
    }
}
